package com.hanserwei.community.controller;

import com.hanserwei.community.entity.common.ApiResponse;
import com.hanserwei.community.entity.request.menu.MenuAddRequest;
import com.hanserwei.community.entity.request.menu.MenuUpdateRequest;
import com.hanserwei.community.entity.vo.MenuVO;
import com.hanserwei.community.service.MenuService;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/menu")
@RequiredArgsConstructor
public class MenuController {

    private final MenuService menuService;

    @Operation(summary = "根据用户名查询用户菜单", description = "获取用户有权限的菜单树")
    @GetMapping("/listMenu/{username}")
    public ApiResponse<List<MenuVO>> listMenu(@PathVariable String username) {
        List<MenuVO> menuList = menuService.queryMenuByUserName(username);
        return ApiResponse.success(menuList);
    }

    @Operation(summary = "根据角色查询角色菜单", description = "获取角色关联的菜单树")
    @GetMapping("/listRoleMenu/{role}")
    public ApiResponse<List<MenuVO>> listRoleMenu(@PathVariable String role) {
        List<MenuVO> menuList = menuService.queryMenuByRole(role);
        return ApiResponse.success(menuList);
    }

    @Operation(summary = "更新角色菜单关联", description = "更新角色与菜单的关联关系")
    @PutMapping("/updateRoleMenu/{roleId}")
    public ApiResponse<Boolean> updateRoleMenu(@RequestBody List<MenuVO> menuVOList, @PathVariable Integer roleId) {
        boolean result = menuService.updateRoleMenu(menuVOList, roleId);
        return ApiResponse.success(result);
    }

    @Operation(summary = "获取所有菜单树", description = "获取系统中所有菜单的树形结构，用于菜单管理")
    @GetMapping("/tree")
    public ApiResponse<List<MenuVO>> getMenuTree() {
        List<MenuVO> menuTree = menuService.getMenuTree();
        return ApiResponse.success(menuTree);
    }

    @Operation(summary = "添加菜单", description = "添加新的菜单项")
    @PostMapping
    public ApiResponse<Boolean> addMenu(@Valid @RequestBody MenuAddRequest request) {
        boolean result = menuService.addMenu(request);
        return ApiResponse.success(result);
    }

    @Operation(summary = "更新菜单", description = "更新菜单信息")
    @PutMapping
    public ApiResponse<Boolean> updateMenu(@Valid @RequestBody MenuUpdateRequest request) {
        boolean result = menuService.updateMenu(request);
        return ApiResponse.success(result);
    }

    @Operation(summary = "删除菜单", description = "删除菜单项，会检查是否有角色关联")
    @DeleteMapping("/{id}")
    public ApiResponse<Boolean> deleteMenu(@PathVariable Integer id) {
        boolean result = menuService.deleteMenu(id);
        return ApiResponse.success(result);
    }

    @Operation(summary = "根据ID查询菜单详情", description = "获取单个菜单的详细信息")
    @GetMapping("/{id}")
    public ApiResponse<MenuVO> getMenuById(@PathVariable Integer id) {
        MenuVO menu = menuService.getMenuById(id);
        return ApiResponse.success(menu);
    }
}
